import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:talk/api/dio/BaseModel.dart';
import 'package:get/route_manager.dart';

import '../../utils/ToastUtils.dart';
import '../auth/AuthBase.dart';
import 'SPUtils.dart';

// 请求方式
enum HTTPMethod {
  get,
  post,
  put,
  delete,
}

class DioClient {
  //创建单例
  static DioClient? _instance;

  // 新增：静态 getter，用于获取 baseUrl
  static String get baseUrl => _dio.options.baseUrl;

  // 确保DioClient 只有一个实例
  factory DioClient() => _instance ?? (_instance = DioClient._init());

  static Dio _dio = Dio();

  DioClient._init() {
    BaseOptions options = BaseOptions(
      connectTimeout: const Duration(seconds: 10),
      receiveTimeout: const Duration(seconds: 10),
    );
    _dio = Dio(options);
    // _dio.options.baseUrl = KeyString.baseUrl;
    _dio.options.baseUrl = "http://192.168.1.163:3000/gate";
    // _dio.options.baseUrl = "http://43.139.39.5:3000/gate";
    // _dio.options.baseUrl = "http://8.129.167.168/gate";
    // 拦截器
    _dio.interceptors.add(ResponseInterceptor());
    // 日志打印
    _dio.interceptors.add(LogInterceptor(requestBody: true));
  }

  DioClient getInstance({String baseUrl = "http://192.168.1.163:3000/gate"}) {
  // DioClient getInstance({String baseUrl = "http://43.139.39.5:3000/gate"}) {
  // DioClient getInstance({String baseUrl = "http://8.129.167.168/gate"}) {
    _dio.options.baseUrl = baseUrl;
    return this;
  }

  doDio(
      path, {
        required method,
        queryParameters,
        data,
        options,
        cancelToken,
        onReceiveProgress,
        loading,
      }) async {
    if (loading == true) {
      // ToastUtils.showToast("普通 Toast");
      // Get.snackbar('提示', '登录成功');
      // Get.defaultDialog(title: '群童', content: Text('adsfasdfasdfasdfd'));


    }
    Response? response;
    switch (method) {
      case HTTPMethod.get:
        response = await _dio.get(path,
            queryParameters: queryParameters,
            data: data,
            options: options,
            cancelToken: cancelToken,
            onReceiveProgress: onReceiveProgress);
        break;
      case HTTPMethod.post:
        response = await _dio.post(path,
            queryParameters: queryParameters,
            data: data,
            options: options,
            cancelToken: cancelToken,
            onReceiveProgress: onReceiveProgress);
      case HTTPMethod.put:
        response = await _dio.put(path,
            queryParameters: queryParameters,
            data: data,
            options: options,
            cancelToken: cancelToken,
            onReceiveProgress: onReceiveProgress);
      case HTTPMethod.delete:
        response = await _dio.delete(path,
            queryParameters: queryParameters,
            data: data,
            options: options,
            cancelToken: cancelToken);
      default:
    }
    if (path == "/login") {
      return response;
    }
    return BaseModel.fromJson(response?.data);
  }
}

//拦截器
class ResponseInterceptor extends InterceptorsWrapper {
  // 请求时
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) async {
      // String token = SPUtils().getToken();
      // String token = SPUtils.getToken();
      String? token = AuthBase().getToken();
      print('DDDDDDDDDDDDDDDDDD');

    if (options.path != "/login") {
        //请求头赋值
        options.headers["Authorization"] = token;
      }

    return handler.next(options);
  }

// 返回时
  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    ToastUtils.cancelToast;
    //成功
    // print(
    //     "返回数据:地址:${response.requestOptions.uri} \n内容:\n${prettyPrintJson(response.toString())}");
    return handler.resolve(response);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) async {
    ToastUtils.cancelToast;
    print("请求返回报错:${err.requestOptions.uri} 错误信息:${err.response},${err.error}");
    if (err.error.toString().contains("Network is unreachable")) {
      ToastUtils.showToast("网络连接失败");
      return handler
          .resolve(Response(requestOptions: err.requestOptions, data: {
        "code": -2,
        "message": "网络连接失败,请检查网络",
        "data": null,
      }));
    } else if (err.response == null) {
      return handler
          .resolve(Response(requestOptions: err.requestOptions, data: {
        "code": -1,
        "message": "请求报错",
        "data": null,
      }));
    } else {
      Map map = json.decode(err.response.toString());
      if (map["message"] != null) {
        ToastUtils.showErrorToast("${getErrorMessage(map["message"])}");
      }
      if (map["status"] == 401) {
        await Future.delayed(const Duration(milliseconds: 2000));
        if (Get.currentRoute == "/LoginPage" || Get.currentRoute == "/") {
          return;
        }

        return handler
            .resolve(Response(requestOptions: err.requestOptions, data: {
          "code": 401,
          "message": "登录失效，请重新登录",
          "data": null,
        }));
      }
      return handler
          .resolve(Response(requestOptions: err.requestOptions, data: {
        "code": -1,
        "message": "请求报错",
        "data": null,
      }));
    }
  }

  ///错误信息
  getErrorMessage(var message) {
    String errMessage = "请求报错";
    switch (message) {
      case "Token has expired":
        errMessage = "登录过期,请重新登录";
        break;
      case "Invalid username":
        errMessage = "用户不存在";
        break;
    }
    return errMessage;
  }

  //格式化打印json数据
  String prettyPrintJson(String jsonStr) {
    var decodedJson = jsonDecode(jsonStr); // 解析 JSON 字符串
    var encoder = JsonEncoder.withIndent('  '); // 使用 2 个空格缩进格式化
    return encoder.convert(decodedJson);
  }
}